package com.zzh.takeoutapp.activity;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.order.more.CheckListener;
import com.zzh.takeoutapp.adapter.order.more.ItemHeaderDecoration;
import com.zzh.takeoutapp.adapter.order.more.RvListener;
import com.zzh.takeoutapp.adapter.order.more.SortAdapter;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.entity.MoreEntity;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.fragment.SortDetailFragment;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.GsonResolve;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/26.
 */

public class MoreActivity extends BaseActivity implements CheckListener {
    @Bind(R.id.tv_search_cancel)
    TextView tv_search_cancel;
    @Bind(R.id.rv_sort)
    RecyclerView rvSort;
    private SortAdapter mSortAdapter;
    private SortDetailFragment mSortDetailFragment;
    private LinearLayoutManager mLinearLayoutManager;
    private int targetPosition;//点击左边某一个具体的item的位置
    private boolean isMoved;
    private int CURPAGE = 1;//加载页码
    private final String MORE_ACTIVITY = "MoreActivity";
    private List<MoreEntity> moreEntityList;

    @Override
    public void setContent() {
        setContentView(R.layout.fragment_goods);
        ButterKnife.bind(this);
        moreEntityList = new ArrayList<>();
    }

    @Override
    public void initComponent() {
        ServiceUrl.CateIndexService(this,
                "manjian",
                "is_new",
                "0",
                "roof_pei",
                "juli",
                CURPAGE, MORE_ACTIVITY);
        initView();
    }

    private void initView() {
        mLinearLayoutManager = new LinearLayoutManager(this);
        rvSort.setLayoutManager(mLinearLayoutManager);
        DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        rvSort.addItemDecoration(decoration);

    }

    private void initData() {
        /*//获取asset目录下的资源文件
        String assetsData = getAssetsData("sort.json");
        Gson gson = new Gson();
        mSortBean = gson.fromJson(assetsData, SortBean.class);
        List<SortBean.CategoryOneArrayBean> categoryOneArray = mSortBean.getCategoryOneArray();*/
        List<String> list = new ArrayList<>();
        //初始化左侧列表数据
        for (int i = 0; i < moreEntityList.size(); i++) {
            list.add(moreEntityList.get(i).getTitle());
        }
        mSortAdapter = new SortAdapter(this, list, new RvListener() {
            @Override
            public void onItemClick(int id, int position) {
                if (mSortDetailFragment != null) {
                    isMoved = true;
                    targetPosition = position;
                    setChecked(position, true);
                }
            }
        });
        rvSort.setAdapter(mSortAdapter);
        createFragment();
    }

    //从资源文件中获取分类json
    private String getAssetsData(String path) {
        String result = "";
        try {
            //获取输入流
            InputStream mAssets = getAssets().open(path);
            //获取文件的字节数
            int lenght = mAssets.available();
            //创建byte数组
            byte[] buffer = new byte[lenght];
            //将文件中的数据写入到字节数组中
            mAssets.read(buffer);
            mAssets.close();
            result = new String(buffer);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("fuck", e.getMessage());
            return result;
        }
    }


    public void createFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        mSortDetailFragment = new SortDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("right", (ArrayList<? extends Parcelable>) moreEntityList);
        mSortDetailFragment.setArguments(bundle);
        mSortDetailFragment.setListener(this);
        fragmentTransaction.add(R.id.lin_fragment, mSortDetailFragment);
        fragmentTransaction.commit();
    }

    private void setChecked(int position, boolean isLeft) {
        if (isLeft) {
            mSortAdapter.setCheckedPosition(position);
            //此处的位置需要根据每个分类的集合来进行计算
            int count = 0;
            for (int i = 0; i < position; i++) {
                count += moreEntityList.get(i).getChildrens().size();
            }
            count += position;
            mSortDetailFragment.setData(count);
            ItemHeaderDecoration.setCurrentTag(String.valueOf(targetPosition));//凡是点击左边，将左边点击的位置作为当前的tag
        } else {
            if (isMoved) {
                isMoved = false;
            } else
                mSortAdapter.setCheckedPosition(position);
            ItemHeaderDecoration.setCurrentTag(String.valueOf(position));//如果是滑动右边联动左边，则按照右边传过来的位置作为tag

        }
        moveToCenter(position);

    }

    //将当前选中的item居中
    private void moveToCenter(int position) {
        //将点击的position转换为当前屏幕上可见的item的位置以便于计算距离顶部的高度，从而进行移动居中
        View childAt = rvSort.getChildAt(position - mLinearLayoutManager.findFirstVisibleItemPosition());
        if (childAt != null) {
            int y = (childAt.getTop() - rvSort.getHeight() / 2);
            rvSort.smoothScrollBy(0, y);
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        EventbusHelper.register(this);
    }

    @Override
    public void onStop() {
        EventbusHelper.unregister(this);
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        JSONObject jsonObject = event.getMsgJSONObj();
        switch (_msgType) {
            case MORE_ACTIVITY:
                if (jsonObject.optString("message").equals("success")) {
                    JSONObject object = jsonObject.optJSONObject("data");
                    JSONArray array = object.optJSONArray("items");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject1 = array.optJSONObject(i);
                        MoreEntity moreEntity = GsonResolve.jsonString2Bean(jsonObject1.toString(), MoreEntity.class);
                        moreEntityList.add(moreEntity);
                    }
                    initData();
                }
                break;
        }

    }

    @Override
    public void check(int position, boolean isScroll) {
        setChecked(position, isScroll);

    }

    @Override
    public void setListener() {

    }

    @Override
    public void onAfterInit() {

    }

    @OnClick({R.id.tv_search_cancel})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_search_cancel:
                finish_Activity();
                break;
        }
    }
}
